#include "smartlock.h"
#include "main.h"
#include "board_base.h"
#include "bsp_uart.h"
#include "servo.h"
#include "stimer.h"
#define debug_printf(str, ...) UARTx_Printf(&huart1, str, ##__VA_ARGS__)

extern "C" int at_send_data(const uint8_t *txdata, uint16_t size)
{
    #if 0
    UARTx_Printf(&huart1,"[send]size:%d,cmd:\"", size);
    while (size)
    {
        if (*txdata == 0x0D) UARTx_Printf(&huart3,"\\r");
        else if (*txdata == 0x0A) UARTx_Printf(&huart3,"\\n");
        else UARTx_Printf(&huart1,"%c", *txdata);
        txdata++;
        size--;
		
    }
    UARTx_Printf(&huart1,"\"\n");
    #endif
    UARTx_Printn(&huart3, (uint8_t*)txdata, size);
//	  UARTx_Printn(&huart1, (uint8_t*)txdata, size);
    return size;
}

extern "C" void lock_auto_task(void const * argument)
{
    SmartLock *obj = (SmartLock *)argument;
    if (obj->isLocked == false) // 时间到，锁住
    {
        servo1.writeAngle(0);
        obj->isLocked = true;
        // 1s后关闭舵机使能来省电
        stimer_task_set_interval(STIMER_SELF_ID, 1000);
		stimer_task_set_repetitions(STIMER_SELF_ID, 1);
		debug_printf("[smartlock]lock start ...\n\r");
    }
    else // 锁完关电
    {
        servo1.writeEnable(0);
		debug_printf("[smartlock]lock ok\n\r");
    }
}

SmartLock::SmartLock(void)
{
    ledState = 2;
    vbat = 5;
    openLockAngle = 90;
    autoCloseTime = 5000;
    isLocked = true;
}

void SmartLock::setLedState(uint8_t state)
{
    this->ledState = state;
    if (ledState == 0)
    {
        LEDx_Write(LED1, 0);
    }
    else if (ledState == 1)
    {
        LEDx_Write(LED1, 1);
    }
}

/**
 * @brief Lock the smart lock
 * @param state true unlock, false lock
 * @retval true lock
 * @retval false unlock
 */
bool SmartLock::setLockState(bool state)
{
    if (state)//TODO:
    {
        // unlock
        if (this->isLocked == false) // 已经解锁
        {
            return false;
        }
        // 没有解锁，解锁并在一段时间后关闭
        this->isLocked = false;
        servo1.writeEnable(1);
        servo1.writeAngle(this->openLockAngle);
        stimer_task_oneshot(lock_auto_task, this->autoCloseTime, 1,(void*)this);
		debug_printf("[smartlock]unlock start\n\r");
        return false;
    }
    else
    {
        // lock
        if (this->isLocked) // 已经锁住
        {
            return true;
        }
        this->isLocked = true;
        servo1.writeAngle(0);
        // 1秒后关闭使能省电
        stimer_task_oneshot(lock_auto_task, 1000, 1, (void*)this);
        return true;
    }
}
bool SmartLock::lock(void)
{
    return setLockState(true);
}
bool SmartLock::unlock(void)
{
    return setLockState(false);
}

